﻿
@inherits BootstrapInputBase<string>

@if (IsShowLabel)
{
    <BootstrapLabel Value="@DisplayText" ShowLabelTooltip="ShowLabelTooltip" required="@Required" for="@Id" />
}
<div class="dropdown w-100">

    <input id="@Id"
           class="@ClassName"
           data-bs-toggle="dropdown"
           aria-haspopup="true"
           aria-expanded="false"
           autocomplete="off"
           readonly="@ReadOnly"
           value="@InputFilter"
           @attributes="AdditionalAttributes"
           @ref="FocusElement"
           @oninput="OnInputAsync"
           @onblur="OnBlurAsync"
           @onkeydown="OnKeydownAsync"
           disabled="@IsDisabled" />

    <div class="dropdown-menu" aria-labelledby="@Id">

        @if (Items is not null && Items.Any())
        {
            @foreach (var item in Items)
            {
                <a class="dropdown-item h6" href="javascript:;" @onclick=@(_ => SelectItemAsync(item))>
                    @item.Text
                    <small class="mb-0">
                        @item.Value
                    </small>
                </a>
            }
        }
        else
        {
            <a class="dropdown-item disabled">@(Items is null ? "请输入.." : "（未找到）")</a>
        }

    </div>

</div>

@code
{
    List<SelectedItem>? Items;

    SelectedItem? SelectedItem;
    string? InputFilter;
    Dictionary<string, object> Attributes { get; set; } = new Dictionary<string, object>();

    [Parameter]
    public string? Text { get; set; }

    string? _value;

    [Parameter]
    public bool ReadOnly { get; set; }


    protected async Task JObjectAsync(string objName, Func<IJSObjectReference, ValueTask> operateAsync)
    {
        var obj = await JSRuntime.InvokeAsync<IJSObjectReference>("getObject", objName);
        if (obj == null)
        {
            return;
        }
        await operateAsync(obj);
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await base.OnAfterRenderAsync(firstRender);
        if (firstRender)
        {
            await JObjectAsync("PageUtil", utl => utl.InvokeVoidAsync("setAutoComplete", $"#{Id}"));
        }
    }

    protected override void OnParametersSet()
    {
        base.OnParametersSet();
        if (string.IsNullOrWhiteSpace(CurrentValue))
        {
            InputFilter = Text = null;
            return;
        }

        _value = CurrentValue;
        Items = new List<SelectedItem>()
            {
                new SelectedItem("a","zg中国"),
                new SelectedItem("b","mg美国")
            };
        if (Items!.Any(x => x.Value == CurrentValue))
        {
            SelectedItem = Items!
           .FirstOrDefault(p => p.Value.Equals(CurrentValue));
        }
        InputFilter = Text = SelectedItem!.Text;
    }

    protected override void OnInitialized()
    {
        base.OnInitialized();
        if (string.IsNullOrWhiteSpace(CurrentValue))
        {
            return;
        }

        InputFilter = Text;
    }

    async Task OnKeydownAsync(KeyboardEventArgs e)
    {
        if (string.IsNullOrWhiteSpace(InputFilter))
        {
            return;
        }

        if (e.Code == "Enter" || e.Code == "NumpadEnter")
        {
            if (Items?.Count > 0)
            {
                await SelectItemAsync(Items[0]);
            }
        }
    }

    async Task OnInputAsync(ChangeEventArgs e)
    {
        InputFilter = e.Value?.ToString();

        if (InputFilter?.Length >= 1)
        {
            Items = new List<SelectedItem>()
            {
                new SelectedItem("a","zg中国"),
                new SelectedItem("b","mg美国")
            };

            Items = Items.Where(x => x.Text.StartsWith(InputFilter)).ToList();
        }
        else if (string.IsNullOrWhiteSpace(InputFilter))
        {
            CurrentValue = null;
            SelectedItem = null;
            await ValueChanged.InvokeAsync(null);
            Items = null;
        }
    }

    Task OnBlurAsync(FocusEventArgs e)
    {
        InputFilter = (SelectedItem == null ? string.IsNullOrWhiteSpace(CurrentValue) ? null : Text : SelectedItem.Text);
        return Task.CompletedTask;
    }

    Task SelectItemAsync(SelectedItem item)
    {
        SelectedItem = item;
        InputFilter = Text = item.Text;

        CurrentValue = item.Value;
        //await ValueChanged.InvokeAsync(item.Value);

        Items = null;
        //await FocusElement.FocusAsync();

        return Task.CompletedTask;
    }
}
